<script type="text/javascript">//<![CDATA[
XHR.poll(5, '<%=luci.dispatcher.build_url("admin/services/aria2/status")%>', null,
	function(x, data) {
		var tb = document.getElementById('aria2_status');
		if (data && tb) {
			if (data.running) {
				var links = '<em><%:The Aria2 service is running.%></em>';
				if (data.yaaw) {
					links += '<input class="cbi-button mar-10" type="button" value="<%:Open YAAW%>" onclick="openWebUI(\'yaaw\');" />';
				}
				if (data.webui) {
					links += '<input class="cbi-button mar-10" type="button" value="<%:Open WebUI-Aria2%>" onclick="openWebUI(\'webui-aria2\');" />';
				}
				if (data.ariang) {
					links += '<input class="cbi-button mar-10" type="button" value="<%:Open AriaNg%>" onclick="openWebUI(\'ariang\');" />';
				}
				tb.innerHTML = links;
			} else {
				tb.innerHTML = '<em><%:The Aria2 service is not running.%></em>';
			}
		}
	}
);

function randomString(len) {
	len = len || 32;
	var $chars = 'abcdefghijklmnopqrstuvwxyz1234567890';
	var maxPos = $chars.length;
	var pwd = '';
	for (i = 0; i < len; i++) {
		pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
	}
	return pwd;
};

function randomSecret() {
	var Token = document.getElementById("cbid.aria2.main.rpc_secret");
	Token.value = randomString(32);
};

function showRPCURL() {
	var websocket = document.getElementById("use_websocket");
	var protocol = (websocket.checked) ? "ws" : "http";
	var newTextNode = document.getElementById("aria2rpcpath");
	var auth_method = document.getElementById("cbid.aria2.main.rpc_auth_method");
	var auth_port = document.getElementById("cbid.aria2.main.rpc_listen_port");
	if (auth_port.value == "") {
		auth_port_value = "6800"
	} else {
		auth_port_value = auth_port.value
	};
	if (auth_method.value == "token") {
		var auth_token = document.getElementById("cbid.aria2.main.rpc_secret");
		newTextNode.value = protocol + "://token:" + auth_token.value + "@" + document.domain + ":" + auth_port_value + "/jsonrpc";
	} else if (auth_method.value == "user_pass") {
		var auth_user = document.getElementById("cbid.aria2.main.rpc_user");
		var auth_passwd = document.getElementById("cbid.aria2.main.rpc_passwd");
		newTextNode.value = protocol + "://" + auth_user.value + ":" + auth_passwd.value + "@" + document.domain + ":" + auth_port_value + "/jsonrpc";
	} else {
		newTextNode.value = protocol + "://" + document.domain + ":" + auth_port_value + "/jsonrpc";
	}
};

function openWebUI(path) {
	var curWwwPath = window.document.location.href;
	var pathName = window.document.location.pathname;
	var pos = curWwwPath.indexOf(pathName);
	var localhostPath = curWwwPath.substring(0, pos);
	var url = "http:" + localhostPath.substring(window.location.protocol.length) + "/" + path;
	window.open(url)
};
//]]>
</script>
<style>.mar-10 {margin-left: 10px; margin-right: 10px;}</style>
<fieldset class="cbi-section">
	<legend><%:Aria2 Status%></legend>
	<p id="aria2_status">
		<em><%:Collecting data...%></em>
	</p>
</fieldset>
